<template>
  <div class="blog-detail">
    <h1>{{ blog.title }}</h1>

    <!-- 字号调节滑动条 -->
    <div class="font-size-control">
      <label>字体大小：{{ fontSize }}px</label>
      <input type="range" min="12" max="32" v-model.number="fontSize" />
    </div>

    <!-- Markdown 正文内容 -->
    <div
      class="markdown-content"
      v-html="renderedContent"
      :style="{ fontSize: fontSize + 'px' }"
    ></div>
  </div>
</template>

<script>
import axios from 'axios';
import { marked } from 'marked';
import hljs from 'highlight.js'; // 用于代码块高亮
import 'highlight.js/styles/github.css'; // 可选：使用 GitHub 主题样式

// 设置 marked 使用 highlight.js 高亮代码
marked.setOptions({
  highlight: (code, lang) => {
    return hljs.highlight(code, { language: lang || 'plaintext' }).value;
  },
  langPrefix: 'hljs language-'
});

export default {
  data() {
  return {
    blog: {},
    fontSize: 16 // 默认字体大小为 16px
  };
},
  computed: {
    renderedContent() {
      return marked.parse(this.blog.content || '');
    }
  },
  created() {
    this.fetchBlog();
  },
    updated() {
    this.$nextTick(() => {
      // 确保 DOM 更新后再执行高亮
      const codeBlocks = document.querySelectorAll('.markdown-content pre code');
      codeBlocks.forEach(block => {
        hljs.highlightElement(block);
      });
    });
  },
  methods: {
    async fetchBlog() {
      const blogId = this.$route.params.id;

      try {
        const res = await axios.get(`http://localhost:8000/api/blog/${blogId}/`);
        this.blog = res.data;
      } catch (error) {
        console.error('获取博客失败:', error);
        alert('获取博客失败');
      }
    }
  }
};
</script>

<style scoped>
.font-size-control {
  margin: 10px 0;
}

.font-size-control input[type="range"] {
  width: 100%;
}
.markdown-content pre {
  background-color: #f5f5f5;
  padding: 10px;
  border-radius: 4px;
  overflow-x: auto;
}

.markdown-content code {
  font-family: Consolas, Monaco, 'Andale Mono', 'Ubuntu Mono', monospace;
}

.markdown-content pre code {
  display: block;
  white-space: pre;
}
.blog-detail {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
  background-color: #e6f7ff; /* 整个页面背景设为淡蓝色 */
  border-radius: 8px;
  min-height: 100vh;
}

.markdown-content {
  white-space: pre-line;
  font-family: sans-serif;
  line-height: 1.6;
  text-align: left;
  background-color: #e6f7ff; /* 淡蓝色背景 */
  padding: 15px;
  border-radius: 4px;
  border: 1px solid #ccc;
  margin-top: 20px;
}

.markdown-content h1, .markdown-content h2, .markdown-content h3 {
  border-bottom: 1px solid #eee;
  padding-bottom: 5px;
  margin-top: 20px;
}

.markdown-content img {
  max-width: 100%;
}
</style>